package cn.fan.springboot_easyexcle.util;


import cn.fan.springboot_easyexcle.interfac.EasyRealInterface;
import cn.fan.springboot_easyexcle.listener.EasyExcelLister;
import cn.fan.springboot_easyexcle.model.JsonMessage;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * 这个是读取exl的工具类
 */
@Slf4j
public class EasyExcelReadUtil {


    //    public static JsonMessage easyRead(EasyRealInterface easyRealInterface, String fileName, Class cls, String errfilepath) {
//        try {
//            // 写法2：
//            easyRealInterface.setErrcla(cls);
//            ExcelReader excelReader = EasyExcel.read(fileName,cls, new EasyExcelLister(easyRealInterface)).build();
//            ReadSheet readSheet = EasyExcel.readSheet(0).build();
//            excelReader.read(readSheet);
//            // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
//            excelReader.finish();
//           return easyRealInterface.finish(errfilepath);
//        } catch (Exception e) {
//            log.error(easyRealInterface.getreportName() + "读取excel异常", e);
//            return new JsonMessage(false,"服务器异常,请重新上传");
//        }
//    }
    public static JsonMessage easyRead(EasyRealInterface easyRealInterface, InputStream inputStream, Class cls, String errfilepath) {
        try {
            easyRealInterface.setErrcla(cls);
            ExcelReader excelReader = EasyExcel.read(inputStream, cls, new EasyExcelLister(easyRealInterface)).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
            excelReader.finish();
            return easyRealInterface.finish(errfilepath);
        } catch (Exception e) {
            log.error(easyRealInterface.getreportName() + "读取excel异常", e);
            return new JsonMessage(false, "服务器异常,请重新上传");
        }
    }

    public static JsonMessage easyRead(EasyRealInterface easyRealInterface, InputStream inputStream, Class cls, HttpServletResponse response) {
        try {
            easyRealInterface.setErrcla(cls);
            ExcelReader excelReader = EasyExcel.read(inputStream, cls, new EasyExcelLister(easyRealInterface)).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
            excelReader.finish();
            return easyRealInterface.finish(response);
        } catch (Exception e) {
            log.error(easyRealInterface.getreportName() + "读取excel异常", e);
            return new JsonMessage(false, "服务器异常,请重新上传");
        }
    }
}
